package parallels.servertech.client.commands;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

import parallels.servertech.client.CommandContext;
import parallels.servertech.client.CommandHandler;

public class ConnectHandler implements CommandHandler {
	private static final String DEFAULT_HOST = "localhost";
	private static final int DEFAULT_PORT = 8080;
	private static final int CONNECT_TIMEOUT = 5000;
	private static final int SOCKET_TIMEOUT = 1000;
	
	@Override
	public void handle(String[] args, CommandContext ctx) {
		String host = DEFAULT_HOST;
		int port = DEFAULT_PORT;
		
		if (args.length > 0) {
			String[] hostAndPort = args[0].split(":");
			host = hostAndPort[0];
			if (hostAndPort.length > 1) {
				port = Integer.parseInt(hostAndPort[1]);
			}
		}
		
		ctx.getOut().printf("connecting to server %s:%d%n", host, port);
		try {
			Socket socket = new Socket();
			socket.connect(new InetSocketAddress(host, port), CONNECT_TIMEOUT);
			
			socket.setSoTimeout(SOCKET_TIMEOUT);
			ctx.connect(socket);
			
			ctx.getOut().println("connected");
		} catch (IOException ioe) {
			ctx.getOut().printf("failed to connect: %s%n", ioe.getMessage());
		}
	}
}
